<template>
  <!-- 退瓶消单 -->
  <el-dialog
    v-el-drag-dialog
    title="退瓶消单"
    :visible.sync="visible"
    width="800px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-width="100px" label-position="right">
      <el-form-item label="收 款 人" style="width: 50%;"><el-input v-model="temp.depReceiver" disabled /></el-form-item>
      <el-form-item label="收款方式" style="width: 50%;"><el-input v-model="calcType" disabled /></el-form-item>
      <el-form-item label="押瓶机构" style="width: 50%;"><el-input v-model="temp.ckOrgName" disabled /></el-form-item>
      <el-form-item label="责任机构" prop="orgSNNo" style="width: 50%;">
        <el-tree-select
          v-model="temp.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="开始时间" style="width: 50%;"><el-input v-model="startDt" disabled /></el-form-item>
      <el-form-item label="结束时间" style="width: 50%;">
        <el-date-picker
          v-model="endDt"
          style="width: 100%;"
          type="date"
          :clearable="false"
          placeholder="选择日期"
        />
      </el-form-item>
      <el-form-item label="审核时间" style="width: 50%;"><el-input v-model="auditDt" disabled /></el-form-item>
      <el-form-item label="消单时间" style="width: 50%;">
        <el-date-picker
          v-model="operateDt"
          style="width: 100%;"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          :clearable="false"
          placeholder="选择日期"
        />
      </el-form-item>
      <div style="width: 100%; margin-bottom: 30px; color: red;">{{ '(开始时间至结束时间共计' + day + ')' }}</div>
      <el-form-item label="总 押 金" style="width: 50%;"><el-input v-model="temp.totalDeposit" disabled /></el-form-item>
      <el-form-item label="总 租 金" style="width: 50%;">
        <el-input v-model="params.totalRental" placeholder="请输入" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" />
      </el-form-item>
      <el-form-item label="应退金额" style="width: 50%;"><el-input v-model="temp.totalDeposit" disabled /></el-form-item>
      <el-form-item label="实退金额" style="width: 50%;">
        <el-input v-model="params.accReturnDeposit" placeholder="请输入" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" />
      </el-form-item>
      <div style=" margin-bottom: 30px; color: red;">特别提示:【消单时间】即为回瓶确认时间,如若对应机构启用了库存此时的【消单时间】将直接影响库存变化</div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  // import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import { queryMap, queryCashPledgeInventory } from '@/api'
  import { mapGetters } from 'vuex'

  export default {
    name: 'TurnOrder',
    data() {
      return {
        visible: false,
        day: '',
        treeData: [],
        endDt: new Date(),
        operateDt: new Date(),
        params: {
          totalRental: '',
          accReturnDeposit: ''
        },
        temp: {
          orgSNNo: '' // 所属机构orgSNNo
        },
        calcTypeList: [],
        rules: {
          orgSNNo: [{ required: true, message: '请选择责任机构', trigger: 'change' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ]),
      // 收款方式
      calcType: function() {
        return formatColumnMap(this.calcTypeList, 'value', this.temp.calcType, 'desc')
      },
      // 开始时间
      startDt: function() {
        return this.temp.beginDt && parseTime(this.temp.beginDt, '{y}-{m}-{d}')
      },
      // 审核时间
      auditDt: function() {
        return this.temp.auditDt && parseTime(this.temp.auditDt, '{y}-{m}-{d} {h}:{i}:{s}')
      }
      // 应退金额  总押金减去总租金
      // money: function() {
      //   return this.temp.totalDeposit - this.temp.totalRental
      // }
    },
    watch: {
      endDt: {
        handler(newName, oldName) {
          console.log('newName', newName)
          if (Date.parse(this.endDt) < Date.parse(this.temp.beginDt)) {
            this.$message({
              type: 'warning',
              message: '结束时间不能小于开始时间!'
            })
            return
          }
          // 处理开始时间和结束时间差
          const numDt = (Date.parse(this.endDt) * 1) - (Date.parse(this.temp.beginDt) * 1)
          if (this.temp.calcType === 3) {
            this.day = `${Math.floor(numDt / 30 / 60 / 60 / 24 / 1000) + 1}个自然月`
          } else {
            this.day = `${Math.floor(numDt / 60 / 60 / 24 / 1000)}天`
          }
        }
        // immediate: true
      }
    },
    async created() {
      await this.getTreeData()
      await this.queryOptionsMap()
    },
    methods: {
      open(temp) {
        console.log('temp', temp)
        this.params.depositCode = temp.depositCode
        this.temp = temp
        // 处理开始时间和结束时间差
        const numDt = (Date.parse(this.endDt) * 1) - (Date.parse(this.temp.beginDt) * 1)
        if (temp.calcType === 3) {
          this.day = `${Math.floor(numDt / 30 / 60 / 60 / 24 / 1000) + 1}个自然月`
        } else {
          this.day = `${Math.floor(numDt / 60 / 60 / 24 / 1000)}天`
        }
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      success() {
        this.$refs.dataForm.validate(async(valid) => {
          if (!valid) return
          if (Date.parse(this.endDt) < Date.parse(this.temp.beginDt)) {
            this.$message({
              type: 'warning',
              message: '结束时间不能小于开始时间!'
            })
            return
          }
          if (Date.parse(this.operateDt) > new Date()) {
            this.$message({
              type: 'warning',
              message: '消单时间不能大于当前时间'
            })
            return
          }
          if (Date.parse(this.operateDt) < Date.parse(this.temp.auditDt)) {
            this.$message({
              type: 'warning',
              message: '消单时间不能小于审核时间'
            })
            return
          } else {
            this.params.operateDt = this.operateDt
          }
          if (!this.params.totalRental) {
            this.$message({
              type: 'warning',
              message: '请输入总租金'
            })
            return
          }
          if (!this.params.accReturnDeposit) {
            this.$message({
              type: 'warning',
              message: '请输入实退金额'
            })
            return
          }
          if (this.params.accReturnDeposit * 1 > this.temp.totalDeposit * 1) {
            this.$message({
              type: 'warning',
              message: '实退金额不能大于应退金额'
            })
            return
          }
          console.log('params', this.params)
          const { status } = await queryCashPledgeInventory({
            returnOrgId: this.params.returnOrgId,
            returnOrgName: this.params.returnOrgName,
            returnOrgSNNo: this.params.orgSNNo,
            depositCode: this.params.depositCode,
            endDt: this.endDt,
            operateDt: this.params.operateDt,
            totalRental: this.params.totalRental,
            accReturnDeposit: this.params.accReturnDeposit
          })
          console.log('退瓶消单', status)
          if (status === 200) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.$emit('turnUpDataTable')
            this.visible = false
          }
        })
      },
      reset() {
        // 初始化时间
        this.endDt = new Date()
        this.operateDt = new Date()
        this.day = ''
        this.params.totalRental = ''
        this.params.accReturnDeposit = ''
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      },
      // 收款方式
      async queryOptionsMap() {
        try {
          const { data } = await queryMap({ enumName: 'CalcType' })
          this.calcTypeList = data
          console.log('查看', this.calcTypeList)
        } catch (error) {
          console.log(error)
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.temp.orgSNNo = value.orgSNNo
        this.params.orgSNNo = value.orgSNNo
        this.params.returnOrgId = value.orgId
        this.params.returnOrgName = value.orgName
      }
    }
  }
</script>

<style lang='scss' scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
</style>
